package com.agnes.network.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;

/**
 * Desc:
 * Creator ling
 * Date:   2017/5/19 0019 18:41
 */

public class NetUtils {
    /**
     * 判断网络是否连接
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager cm = getConnectivityManager(context);
        if (null != cm) {
            NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                if (activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是不是WiFi连接
     */
    public static boolean isWifi(Context context) {
        ConnectivityManager cm = getConnectivityManager(context);
        if (null != cm) {
            NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
            if (null != activeNetworkInfo
                && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是不是移动网络连接
     */
    public static boolean isMobile(Context context) {
        ConnectivityManager cm = getConnectivityManager(context);
        if (null != cm) {
            NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
            if (null != activeNetworkInfo
                && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                return true;
            }
        }
        return false;
    }

    private static ConnectivityManager getConnectivityManager(Context context) {
        return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    /**
     * 打开网络设置界面
     * 判断手机系统的版本！如果API大于10 就是3.0+
     * 因为3.0以上的版本的设置和3.0以下的设置不一样，调用的方法不同
     */
    @SuppressLint("ObsoleteSdkInt")
    public static void openSetting(Activity activity) {
        Intent intent = null;
        if (Build.VERSION.SDK_INT > 10) {
            intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
            /*intent = new Intent(Settings.ACTION_SETTINGS);*/
        } else {
            intent = new Intent();
            ComponentName cm =
                new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
            intent.setComponent(cm);
            intent.setAction("android.intent.action.VIEW");
        }

        activity.startActivityForResult(intent, 0);
    }
}
